﻿using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using Prism.Events;

namespace PrismApp.ViewModels
{
    // 第一种情况：处理数据、值验证（ErrorsContainer）
    // 第二种情况：处理命令
    public class FirstWindowVM : BindableBase, INotifyDataErrorInfo
    {
        public FirstWindowVM(IEventAggregator ea)
        {
            MyProperty = "123";
        }

        private string _myProperty;
        public string MyProperty
        {
            get { return _myProperty; }
            set
            {
                //_myVar = value;

                //1.第一种方式
                //this.RaisePropertyChanged();
                //通知其他属性
                this.RaisePropertyChanged("其他属性名称");

                //2.第二种方式
                //this.SetProperty(ref myVar, value, "MyProperty");
                this.SetProperty<string>(ref _myProperty, value,() =>
                {
                    //onChanged
                });

                //基于ErrorsContainer的数据校验方式
                if (value == "1234")
                {
                    //异常消息
                    ErrorsContainer.SetErrors("MyProperty", new string[] { "输入值无效1234" });
                }
                else
                {
                    ErrorsContainer.ClearErrors("MyProperty");
                }
            }
        }

       
        //OnPropertyChanged;
        //CanExecuteChanged;
        private ErrorsContainer<string> _errorsContainer;
        public ErrorsContainer<string> ErrorsContainer
        {
            get
            {
                if (_errorsContainer == null)
                {
                    _errorsContainer = new ErrorsContainer<string>((propName) =>
                    {
                        // 异常信息的处理
                        ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propName));
                    });
                }
                return _errorsContainer;
            }
            set
            {
                _errorsContainer = value;
            }
        }

        #region INotifyDataErrorInfo members
        /// <summary>
        /// INotifyDataErrorInfo接口方法
        /// </summary>
        public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;

        /// <summary>
        /// INotifyDataErrorInfo接口方法
        /// </summary>
        public bool HasErrors
        { 
            get
            { 
                return ErrorsContainer.HasErrors;
            }
        }

        /// <summary>
        /// INotifyDataErrorInfo接口方法
        /// </summary>
        public IEnumerable GetErrors(string propertyName)
        { 
            return ErrorsContainer.GetErrors(propertyName);
        }
        #endregion
    }
}
